﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Carer.Crm.Utility
{
    public static class ObjectExtend
    {
        /// <summary>
        /// 取得值K轉型，若o法轉型t回泛型型e的 defaulValue
        /// </summary>
        /// <typeparam name="T">泛型</typeparam>
        /// <param name="obj">所有物件</param>
        /// <returns>泛型回髦?/returns>
        public static T ToGetValue<T>(this object obj)
        {
            return obj.ToGetValue(default(T));
        }

        /// <summary>
        /// 取得值K轉型，若o法轉型t回 defaulValue
        /// </summary>
        /// <typeparam name="T">泛型</typeparam>
        /// <param name="obj">所有物件</param>
        /// <param name="defaultValue">預設值</param>
        /// <returns>泛型回髦?/returns>
        public static T ToGetValue<T>(this object obj, T defaultValue)
        {
            if (!(typeof(T) == typeof(string)))
            {
                return obj.ToConvert(defaultValue);
            }
            T t = obj.ToConvert(defaultValue);
            if (t == null)
            {
                return defaultValue;
            }
            return t;
        }


        /// <summary>
        /// 轉Q值型e镋num
        /// </summary>
        /// <typeparam name="TEnum">泛型Enum</typeparam>
        /// <param name="item"></param>
        /// <returns>泛型Enum</returns>
        public static TEnum ToEnumOrDefault<TEnum>(this object item)
        {
            TEnum result;
            try
            {
                object obj = Enum.Parse(typeof(TEnum), item.ToString());
                result = (TEnum)((object)obj);
            }
            catch
            {
                result = Activator.CreateInstance<TEnum>();
            }
            return result;
        }

        /// <summary>
        /// 轉型，D型失回黝A設值
        /// </summary>
        /// <typeparam name="T">泛型</typeparam>
        /// <param name="obj">所有物件</param>
        /// <param name="defaultValue">預設值</param>
        /// <returns>泛型回髦?/returns>
        private static T ToConvert<T>(this object obj, T defaultValue)
        {
            T result;
            try
            {
                Type type = typeof(T);
                if (type.IsValueType && !type.IsPrimitive && type.IsGenericType)
                {
                    type = type.GetGenericArguments()[0];
                }
                result = (T)((object)Convert.ChangeType(obj, type));
            }
            catch
            {
                result = defaultValue;
            }
            return result;
        }

    }
}
